<?php
namespace control;

// 选项设置
class optionSettingClass extends adIndexClass
{
    private const page = 'optionSetting';
    private const table = 'option_setting';
    private const title = '选项设置';
    private array $numOption = [1, 2, 3, 4, 5, 6, 7, 8];

    /*编码入口页*/
    public function home(): string
    {
        $type = $this->get('type') ?: '公共';
        $search = '<i class="container-left-search-ico"></i>' . text(["name" => 'name', 'title' => "类型", 'class' => 'container-left-search', 'keyup' => 'search_left']);
        $space = space;
        $all = $this->getPowerAll();
        //返回
        $rightHtml = $this->homeRight();
        $html = <<<EOT
        <div class="container-main">
            <div class="container-left left" id="container-left">
                $search $space $all
            </div>
            <div class="container-right left" id="container-detail">
				$rightHtml
            </div>
        </div>
<script>
function search_left(e){
    containerLeftSearch(e,'{$this->get('cla')}')
}
function replaceRightDetail(obj, cla = '{$this->get('cla')}') {
     let api, id = $(obj).attr('data-id')
    if (id.length > 0) {
        let that = $(obj).parent('ul')
        const two = that.attr('pid');
        const one = that.parent('ul').attr('pid');
        // ulScal(obj, id)
        $('#container-left').find('li').removeClass('active')
        $(obj).addClass('active')
        api = root + 'control/adIndex.html?cla=' + cla + '&fun=homeRightJson'
        $.post(api, {
            menuOne:one,
            menuTwo: two,
            menuThree: id
        }, function (data) {
            $('#container-detail').html(data.html)
        }, "json");
    }
}
 function cancelPage(id){
    if (id){
       let obj =  $("[data-id='"+id+"']");
        replaceRightDetail(obj,'optionSetting'); 
    }
}
 $(function (){
     cancelPage('{$type}')
 })
</script>
<style>
.container-left{height: calc(100% - 90px);position: fixed !important;min-height: unset;overflow-y: auto;overflow-x: hidden;}
.container-right{height: calc(100% - 90px);margin-left: 18%;width: 80%}
</style>
EOT;
        //返回
        return $this->homeFun($html);
    }

    public function homeRight(): string
    {
        // 搜索
        $html = hidden(['name' => 'menuThree', 'value' => $this->post('menuThree')]);
        return $this->search($html, otherButton: 'no');
    }

    /**
     * 左侧搜索框
     *
     * @return string
     */
    public function getContainerLeftJson(): string
    {
        $json['html'] = $this->getPowerAll();
        return json_encode($json, 320);
    }

    /**
     * 获取数据
     *
     * @return array
     */
    private function orginalData(): array
    {
        return [
            '公共',
            '销售',
            '采购',
            '委外',
            '物流',
            '库存',
            '核算',
            '生产',
            '质量',
            '往来账/出纳',
            '总账',
        ];
    }

    public function getPowerAll(array $local = [], string $pid = ''): string
    {
        $result = $local ?: $this->orginalData();
        $style = empty($pid) ? 'pid=0' : ' class="child-node"';
        $temp = "<ul $style $pid>";
        // 角标
        $arrow = "<span class='arrow'  onclick=\"liZoom($(this).parent())\"></span>";
        $lastone = lastone;
        foreach ($result as $key => $value) {
            // 判断下级是否存在
            $pid = "pid=$value";
            if (is_array($value)) {
                $temp .= "<li data-id='$key' onclick=\"replaceRightDetail(this)\">$arrow $key</li>";
                $temp .= $this->getPowerAll($value, $pid);
            } else {
                $temp .= "<li data-id='$value' onclick=\"replaceRightDetail(this)\">$lastone $value</li>";
            }
        }
        $temp .= '</ul>';
        return $temp;
    }

    /**
     * 异步加载
     */
    public function homeRightJson(): string
    {
        $json['html'] = $this->homeRight();
        return json_encode($json, 320);
    }

    public function homeRightJsonSearch(): string
    {
        return $this->homeSearch();
    }


    /**
     * 获取选项设置
     * @param $type
     * @return array
     */
    public static function getSetting($type): array
    {
        $settingInfo = query('option_setting', "type = '$type' and coid = '" . self::$coid . "'");
        $setting = json_decode($settingInfo['setting'], true);
        if (!$settingInfo['id'] || !$setting || !is_array($setting)) {
            return [];
        } else {
            return $setting;
        }
    }

    /**
     * 获取选项值
     * @param $type
     * @param $key
     * @return mixed
     */
    public static function getSettingItem($type, $key): mixed
    {
        $settingInfo = query('option_setting', "type = '$type' and coid = '" . self::$coid . "'");
        $setting = json_decode($settingInfo['setting'], true);
        if (!$settingInfo['id'] || !$setting || !is_array($setting)) {
            return 0;
        } else {
            if (isset($setting[$key])) {
                return $setting[$key];
            } else {
                return 0;
            }
        }
    }

    /*列表页-查询结果*/
    public function homeSearch(): bool|string
    {
        $type = $this->post('menuThree');
        $json['html'] = match ($type) {
            '总账' => $this->accountTotal($type),
            '往来账/出纳' => $this->currentAccount($type),
            '质量' => $this->qualityOrder($type),
            '生产' => $this->machiningOrder($type),
            '核算' => $this->accounting($type),
            '库存' => $this->inventoryOrder($type),
            '物流' => $this->logistics($type),
            '委外' => $this->outsource($type),
            '采购' => $this->purchase($type),
            '销售' => $this->sale($type),
            '公共' => $this->publicSetting($type),
            default => '未找到类型',
        };
        //返回
        $json['html'] .= <<<eof
<style>
.small-title{margin-left: 0 !important;}
</style>
eof;

        return json_encode($json, 320);
    }

    /**
     * 公共
     * @param $type
     * @return string
     */
    private function publicSetting($type): string
    {
        //数据查询
        $info = query(self::table, " coid = '".self::$coid."' and type = '" . $type . "' ");
        $setting = [
            'companyRepeatCtrl' => '',
            'companyRepeatItemCtrl' => [],
            'companyCanStop' => 0,
            'showBomCatalog' => 0,
            'materialCode' => 0,
            'materialRepeatDeal' => [
                'option' => 0,
                'method' => ''
            ],
            'materialStop' => 0,
            'materialRate' => 0,
            'numPrecision' => [
                'num' => '',
                'numLostZero' => 0
            ],
            'pricePrecision' => [
                'num' => '',
                'priceLostZero' => 0
            ],
            'conversionRate' => 0,
            'invoicePrice' => 0,
            'lossRate' => 0,
            'depreciationrate' => 0,
            'barcodeCtrl' => [
                'option' => 0,
                'merge' => 0
            ],
            'batchCtrl' => [
                'option' => 0,
                'period' => 0,
                'auto' => 0
            ],
        ];
        $setting = $info['setting'] ? json_decode($info['setting'], true) : $setting;
        //按钮
        $button = [];
        if ($this->power(self::page, "edit")) {
            $button[] = [
                "name" => "保存",
                "type" => "点击事件",
                "fun" => "subForm('" . self::page . "HomeRightJsonSearchForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=publicSettingEdit')",
                'style' => 'li-btn-blue-bg',
            ];
        }
        $url = root . 'control/adIndex.html?cla=codeTemplate&fun=home';
        //生成表单
        return $this->layerEdit([
            "table" => [
                [
                    $this->tableShowButton($button),
                ],
                [
                    "<span class='small-title'>基础数据</span>"
                ],
                [
                    "往来单位重复控制&emsp;" . radio(array('name' => 'companyRepeatCtrl', 'value' => ['提示', '禁止'], 'checked' => $setting['companyRepeatCtrl']))
                ],
                [
                    "往来单位重复检查项&emsp;" . checkbox(array('name' => 'companyRepeatItemCtrl', 'value' => ['companyName' => '名称', 'contactName' => '常用联系人', 'contactTel' => '常用联系人电话'], 'checked' => $setting['companyRepeatItemCtrl']))
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('companyCanStop', 1, '往来单位应收应付有余额时可以停用', $setting['companyCanStop'])
                ],

                [
                    businessVoucherSettingClass::singleCheckBox('showBomCatalog', 1, '物料清单分类数展示', $setting['showBomCatalog']) . componentClass::tipComponent("勾选时展示物料清单左侧分类树，不勾选时不展示")
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('materialCode', 1, '存货编码可以修改', $setting['materialCode']) . componentClass::tipComponent("勾选已经使用的物料，编码可以修改，不勾选时已经使用的物料，编码不能修改")
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('materialRepeatDeal', 1, '物料导入检查到重复处理方式', $setting['materialRepeatDeal']['option']) . "&emsp;" . radio(array('name' => 'materialRepeatDealMethod', 'value' => ['cover' => '覆盖', 'ban' => '禁止导入'], 'checked' => $setting['materialRepeatDeal']['method']))
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('materialStop', 1, '存货库存有余额时可以停用', $setting['materialStop'])
                ],
                /*[
                    businessVoucherSettingClass::singleCheckBox('materialRate', 1, '浮动换算率存货，修改数量时，优先反算换算率', $setting['materialRate'])
                ],*/
                [
                    "<span class='small-title'>数据精度</span>"
                ],
                [
                    "数量小数位：" . select(array('name' => 'numPrecision', 'value' => $setting['numPrecision']['num'], 'option' => $this->numOption)) . "&emsp;" . businessVoucherSettingClass::singleCheckBox('numLostZero', 1, '舍零', $setting['numPrecision']['numLostZero'])
                ],
                [
                    "单价小数位：" . select(array('name' => 'pricePrecision', 'value' => $setting['pricePrecision']['num'], 'option' => $this->numOption)) . "&emsp;" . businessVoucherSettingClass::singleCheckBox('priceLostZero', 1, '舍零', $setting['pricePrecision']['priceLostZero'])
                ],
                [
                    "损耗率小数位：" . select(array('name' => 'lossRate', 'value' => $setting['lossRate'], 'option' => $this->numOption))
                ],
                /*[
                    "换算率小数位：" . select(array('name' => 'conversionRate', 'value' => $setting['conversionRate'], 'option' => $this->numOption))
                ],
                [
                    "发票单价小数位：" . select(array('name' => 'invoicePrice', 'value' => $setting['invoicePrice'], 'option' => $this->numOption))
                ],
                [
                    "折旧率小数位：" . select(array('name' => 'depreciationrate', 'value' => $setting['depreciationrate'], 'option' => $this->numOption))
                ],
                [
                    "<span class='small-title'>条形码管理</span>"
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('barcodeCtrl', 1, '条形码管理', $setting['barcodeCtrl']['option'])
                ],
                [
                    "&emsp;" . businessVoucherSettingClass::singleCheckBox('barcodeMerge', 1, '扫描条码时相同明细合并', $setting['barcodeCtrl']['merge'])
                ],*/
                [
                    "<span class='small-title'>批号管理</span>"
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('batchCtrl', 1, '批号管理', $setting['batchCtrl']['option']) . componentClass::tipComponent("勾选物料档案中显示批号管理字段，否则不显示")
                ],
                [
                    "&emsp;" . businessVoucherSettingClass::singleCheckBox('batchQuality', 1, '保质期管理', $setting['batchCtrl']['period']) . componentClass::tipComponent("勾选物料档案中显示保质期管理字段，否则不显示")
                ],
                [
                    "&emsp;" . businessVoucherSettingClass::singleCheckBox('batchCtrlAuto', 1, '批号自动生成', $setting['batchCtrl']['auto']) . "<span class='spanButton' onclick=\"newIframe('编码设置','$url')\" style='margin-top: 0;color: #4C9CFB !important;border-color: #4C9CFB !important;padding: 0 20px'>批号生成规则</span>" . componentClass::tipComponent("在编码规则中配置")
                ],
            ],
            'hidden' => hidden(array('name' => 'type', 'value' => $type)) . hidden(array('name' => 'id', 'value' => $info['id'] ?: suiji())),
            'button' => ' ',
        ]);
    }

    /**
     * 公共
     * @return false|string
     */
    public function publicSettingEdit()
    {
        $id = $this->post('id');
        $setting = [
            'quoteWithTax' => $this->post('quoteWithTax') ?: 0,
            'companyRepeatCtrl' => $this->post('companyRepeatCtrl') ?: '',
            'companyRepeatItemCtrl' => $this->post('companyRepeatItemCtrl') ?: [],
            'companyCanStop' => $this->post('companyCanStop') ?: 0,
            'showBomCatalog' => $this->post('showBomCatalog') ?: 0,
            'materialCode' => $this->post('materialCode') ?: 0,
            'materialRepeatDeal' => [
                'option' => $this->post('materialRepeatDeal') ?: 0,
                'method' => $this->post('materialRepeatDealMethod') ?: ''
            ],
            'materialStop' => $this->post('materialStop') ?: 0,
            'materialRate' => $this->post('quoteWithTax') ?: 0,
            'numPrecision' => [
                'num' => $this->post('numPrecision') ?: '',
                'numLostZero' => $this->post('numLostZero') ?: 0
            ],
            'pricePrecision' => [
                'num' => $this->post('pricePrecision') ?: '',
                'priceLostZero' => $this->post('priceLostZero') ?: 0
            ],
            'conversionRate' => $this->post('conversionRate') ?: 0,
            'invoicePrice' => $this->post('invoicePrice') ?: 0,
            'lossRate' => $this->post('lossRate') ?: 0,
            'depreciationrate' => $this->post('depreciationrate') ?: 0,
            'barcodeCtrl' => [
                'option' => $this->post('barcodeCtrl') ?: 0,
                'merge' => $this->post('barcodeMerge') ?: 0
            ],
            'batchCtrl' => [
                'option' => $this->post('batchCtrl') ?: 0,
                'period' => $this->post('batchQuality') ?: 0,
                'auto' => $this->post('batchCtrlAuto') ?: 0
            ],
        ];
        //赋值
        $field = [
            "type" => $this->post('type'),
            'setting' => json_encode($setting, 320)
        ];
        $annotation = [
            'type' => '类型',
        ];
        $rules = [
            'type' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }

        $info = query(self::table, " id = '" . $id . "' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑的权限";
        } elseif (empty($id)) {
            $json['warn'] = "ID号为空";
        } elseif (empty($info['id'])) {
            $field = array_merge($field, ["id" => $id, 'coid' => self::$coid]);
            $json['warn'] = insert(["table" => self::table, "field" => $field]);
        } else {
            $json['warn'] = update(["table" => self::table, "field" => $field, "where" => "id = '" . $id . "'"]);
        }
        if (in_array($json['warn'], array("新增成功", "更新成功"))) {
            //添加日志
            $type = mb_substr($json['warn'], 0, 2, 'utf-8');
            $text = $this->control['name'] . $type . "了一个选项设置：" . $id;
            $this->logText(array("type" => self::page, "text" => $text));
            //提示
            $_SESSION['warn'] = $json['warn'];
            $json['warn'] = 2;
            $json['href'] = root . 'control/adIndex.html?cla=' . self::page . '&fun=home&type=' . $field['type'];
        }
        //返回
        resp:
        return json_encode($json, 320);
    }


    /**
     * 销售
     * @param $type
     * @return string
     */
    private function sale($type): string
    {
        //数据查询
        $info = query(self::table, " coid = '".self::$coid."' and type = '" . $type . "' ");
        $setting = [
            'quoteWithTax' => 0,
            'saleStrict' => 0,
            'machiningStrick' => 0,
            'saleWithOrder' => 0,
            'refundWithOrder' => 0,
            'autoOut' => 0,
            'checkRepeat' => 0,
            'ctrlUnit' => 0,
            'ctrlSale' => 0,
            'creditCtrl' => [
                'option' => 0,
                'way' => '',
                'bookingMoney' => '',
                'saleMoney'=>''
            ],
            'salePriceCtrl' => [
                'option' => 0,
                'way' => '',
                'method' => ''
            ],
        ];
        $setting = $info['setting'] ? json_decode($info['setting'], true) : $setting;
        //按钮
        $button = [];
        if ($this->power(self::page, "edit")) {
            $button[] = [
                "name" => "保存",
                "type" => "点击事件",
                "fun" => "subForm('" . self::page . "HomeRightJsonSearchForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=saleEdit')",
                'style' => 'li-btn-blue-bg',
            ];
        }

        //生成表单
        return $this->layerEdit([
            "table" => [
                [
                    $this->tableShowButton($button),
                ],
                [
                    "<span class='small-title'>基础业务</span>"
                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('quoteWithTax', 1, '报价含税', $setting['quoteWithTax'])
//                ],
                [
                    businessVoucherSettingClass::singleCheckBox('saleStrict', 1, '按订单严格销售', $setting['saleStrict'])
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('machiningStrick', 1, '按订单严格生产', $setting['machiningStrick'])
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('saleWithOrder', 1, '普通销售必有订单', $setting['saleWithOrder'])
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('refundWithOrder', 1, '销售退货必有订单', $setting['refundWithOrder'])
                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('autoOut', 1, '销售发货单自动出库', $setting['autoOut'])
//                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('checkRepeat', 1, '录入存货时检测存货重复录入', $setting['checkRepeat'])
//                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('ctrlUnit', 1, '非销售业务选择销售订单控制往来单位数据权限', $setting['ctrlUnit'])
//                ],
                [
                    businessVoucherSettingClass::singleCheckBox('ctrlSale', 1, '控制允销限销', $setting['ctrlSale'])
                ],
                [
                    "<span class='small-title'>信用控制</span>"
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('creditCtrl', 1, '客户信用额度控制', $setting['creditCtrl']['option'])
                ],
                [
                    "&emsp;控制时机&emsp;" . radio(array('name' => 'creditCtrlWay', 'value' => ['保存', '复核'], 'checked' => $setting['creditCtrl']['way']))
                ],
                [
                    "&emsp;信用额度占用 =&emsp;" . businessVoucherSettingClass::singleCheckBox('bookingMoney', 1, '已订未出货', $setting['creditCtrl']['bookingMoney']) . "&nbsp;+&nbsp;" . businessVoucherSettingClass::singleCheckBox('saleMoney', 1, '销售应收款', $setting['creditCtrl']['saleMoney']) . "&nbsp;-&nbsp;预收款" // businessVoucherSettingClass::singleCheckBox('creditCtrlVal[]', 1, '预收款', $setting['creditCtrl']['val'][2] ?? '')
                ],
//                [
//                    "<span class='small-title'>最低售价控制</span>"
//                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('salePriceCtrl', 1, '最低售价控制', $setting['salePriceCtrl']['option'])
//                ],
//                [
//                    "&emsp;控制时机&emsp;" . radio(array('name' => 'salePriceCtrlTime', 'value' => ['保存', '复核'], 'checked' => $setting['salePriceCtrl']['way']))
//                ],
//                [
//                    "&emsp;控制方式&emsp;" . radio(array('name' => 'salePriceCtrlMethod', 'value' => ['提交', '密码', '禁止'], 'checked' => $setting['salePriceCtrl']['method']))
//                ],
            ],
            'hidden' => hidden(array('name' => 'type', 'value' => $type)) . hidden(array('name' => 'id', 'value' => $info['id'] ?: suiji())),
            'button' => ' ',
        ]);
    }

    /**
     * 销售
     * @return bool|string
     */
    public function saleEdit(): bool|string
    {
        $id = $this->post('id');
        $setting = [
            'quoteWithTax' => $this->post('quoteWithTax') ?: 0,
            'saleStrict' => $this->post('saleStrict') ?: 0,
            'machiningStrick' => $this->post('machiningStrick') ?: 0,
            'saleWithOrder' => $this->post('saleWithOrder') ?: 0,
            'refundWithOrder' => $this->post('refundWithOrder') ?: 0,
            'autoOut' => $this->post('autoOut') ?: 0,
            'checkRepeat' => $this->post('checkRepeat') ?: 0,
            'ctrlUnit' => $this->post('ctrlUnit') ?: 0,
            'ctrlSale' => $this->post('ctrlSale') ?: 0,
            'creditCtrl' => [
                'option' => $this->post('creditCtrl') ?: 0,
                'way' => $this->post('creditCtrlWay') ?: '',
                'bookingMoney' => $this->post('bookingMoney') ?: '',
                'saleMoney' => $this->post('saleMoney') ?: '',
            ],
            'salePriceCtrl' => [
                'option' => $this->post('salePriceCtrl') ?: 0,
                'way' => $this->post('salePriceCtrlTime') ?: '',
                'method' => $this->post('salePriceCtrlMethod') ?: ''
            ],
        ];
        //赋值
        $field = [
            "type" => $this->post('type'),
            'setting' => json_encode($setting, 320)
        ];
        $annotation = [
            'type' => '类型',
        ];
        $rules = [
            'type' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }

        $info = query(self::table, " id = '" . $id . "' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑的权限";
        } elseif (empty($id)) {
            $json['warn'] = "ID号为空";
        } elseif (empty($info['id'])) {
            $field = array_merge($field, ["id" => $id, 'coid' => self::$coid]);
            $json['warn'] = insert(["table" => self::table, "field" => $field]);
        } else {
            $json['warn'] = update(["table" => self::table, "field" => $field, "where" => "id = '" . $id . "'"]);
        }
        if (in_array($json['warn'], array("新增成功", "更新成功"))) {
            //添加日志
            $type = mb_substr($json['warn'], 0, 2, 'utf-8');
            $text = $this->control['name'] . $type . "了一个选项设置：" . $id;
            $this->logText(array("type" => self::page, "text" => $text));
            //提示
            $_SESSION['warn'] = $json['warn'];
            $json['warn'] = 2;
            $json['href'] = root . 'control/adIndex.html?cla=' . self::page . '&fun=home&type=' . $field['type'];
        }
        //返回
        resp:
        return json_encode($json, 320);
    }

    /**
     * 采购
     * @param $type
     * @return string
     */
    private function purchase($type): string
    {
        //数据查询
        $info = query(self::table, " coid = '".self::$coid."' and type = '" . $type . "' ");
        $setting = [
            'purchaseMustOrder' => 0,
            'refundOrder' => 0,
            'purchaseStrict' => 0,
            'purchaseApplyStrict' => 0,
            'purchaseAutoIn' => 0,
            'checkRepeat' => 0,
            'purchaseBaseWithTax' => 0,
            'purchasePriceCtrl' => [
                'option' => 0,
                'way' => '',
                'method' => ''
            ],
        ];
        $setting = $info['setting'] ? json_decode($info['setting'], true) : $setting;
        //按钮
        $button = [];
        if ($this->power(self::page, "edit")) {
            $button[] = [
                "name" => "保存",
                "type" => "点击事件",
                "fun" => "subForm('" . self::page . "HomeRightJsonSearchForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=purchaseEdit')",
                'style' => 'li-btn-blue-bg',
            ];
        }

        //生成表单
        return $this->layerEdit([
            "table" => [
                [
                    $this->tableShowButton($button),
                ],
                [
                    "<span class='small-title'>基础业务</span>"
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('purchaseMustOrder', 1, '普通采购必有订单', $setting['purchaseMustOrder'])
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('refundOrder', 1, '采购退货必有订单', $setting['refundOrder'])
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('purchaseStrict', 1, '按订单严格采购', $setting['purchaseStrict'])
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('purchaseApplyStrict', 1, '按请购单严格下订单', $setting['purchaseApplyStrict'])
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('purchaseAutoIn', 1, '采购收货单自动入库', $setting['purchaseAutoIn'])
                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('checkRepeat', 1, '录入存货时检测存货重复录入', $setting['checkRepeat'])
//                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('purchaseBaseWithTax', 1, '采购基准价含税', $setting['purchaseBaseWithTax'])
//                ],
//                [
//                    "<span class='small-title'>最高采购价控制</span>"
//                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('purchasePriceCtrl', 1, '最高采购价控制', $setting['purchasePriceCtrl']['option'])
//                ],
//                [
//                    "&emsp;控制时机&emsp;" . radio(array('name' => 'purchasePriceCtrlTime', 'value' => ['保存', '复核'], 'checked' => $setting['purchasePriceCtrl']['way']))
//                ],
//                [
//                    "&emsp;控制方式&emsp;" . radio(array('name' => 'purchasePriceCtrlMethod', 'value' => ['提交', '密码', '禁止'], 'checked' => $setting['purchasePriceCtrl']['method']))
//                ],
            ],
            'hidden' => hidden(array('name' => 'type', 'value' => $type)) . hidden(array('name' => 'id', 'value' => $info['id'] ?: suiji())),
            'button' => ' ',
        ]);
    }

    /**
     * 采购
     * @return false|string
     */
    public function purchaseEdit()
    {
        $id = $this->post('id');
        $setting = [
            'purchaseMustOrder' => $this->post('purchaseMustOrder') ?: 0,
            'refundOrder' => $this->post('refundOrder') ?: 0,
            'purchaseStrict' => $this->post('purchaseStrict') ?: 0,
            'purchaseApplyStrict' => $this->post('purchaseApplyStrict') ?: 0,
            'purchaseAutoIn' => $this->post('purchaseAutoIn') ?: 0,
            'checkRepeat' => $this->post('checkRepeat') ?: 0,
            'purchaseBaseWithTax' => $this->post('purchaseBaseWithTax') ?: 0,
            'purchasePriceCtrl' => [
                'option' => $this->post('purchasePriceCtrl') ?: 0,
                'way' => $this->post('purchasePriceCtrlTime') ?: '',
                'method' => $this->post('purchasePriceCtrlMethod') ?: ''
            ],
        ];
        //赋值
        $field = [
            "type" => $this->post('type'),
            'setting' => json_encode($setting, 320)
        ];
        $annotation = [
            'type' => '类型',
        ];
        $rules = [
            'type' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }

        $info = query(self::table, " id = '" . $id . "' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑的权限";
        } elseif (empty($id)) {
            $json['warn'] = "ID号为空";
        } elseif (empty($info['id'])) {
            $field = array_merge($field, ["id" => $id, 'coid' => self::$coid]);
            $json['warn'] = insert(["table" => self::table, "field" => $field]);
        } else {
            $json['warn'] = update(["table" => self::table, "field" => $field, "where" => "id = '" . $id . "'"]);
        }
        if (in_array($json['warn'], array("新增成功", "更新成功"))) {
            //添加日志
            $type = mb_substr($json['warn'], 0, 2, 'utf-8');
            $text = $this->control['name'] . $type . "了一个选项设置：" . $id;
            $this->logText(array("type" => self::page, "text" => $text));
            //提示
            $_SESSION['warn'] = $json['warn'];
            $json['warn'] = 2;
            $json['href'] = root . 'control/adIndex.html?cla=' . self::page . '&fun=home&type=' . $field['type'];
        }
        //返回
        resp:
        return json_encode($json, 320);
    }

    /**
     * 委外
     * @param $type
     * @return string
     */
    private function outsource($type): string
    {
        //数据查询
        $info = query(self::table, " coid = '".self::$coid."' and type = '" . $type . "' ");
        $setting = [
            'outsourceStrictPick' => 0,
            'outsourceStrictInStock' => 0,
            'outsourceProcessIn' => [
                'option' => 0,
                'method' => ''
            ],
            'reverseCheck' => 0,
            'allowNewMaterial' => 0,
            'bomShowMethod' => 0,
            'outsourceBaseWithTax' => 0,
            'outsourceTaxPrice' => 0,
            'outsourcePriceCtrl' => [
                'option' => 0,
                'way' => '',
                'method' => ''
            ],
        ];
        $setting = $info['setting'] ? json_decode($info['setting'], true) : $setting;
        //按钮
        $button = [];
        if ($this->power(self::page, "edit")) {
            $button[] = [
                "name" => "保存",
                "type" => "点击事件",
                "fun" => "subForm('" . self::page . "HomeRightJsonSearchForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=outsourceEdit')",
                'style' => 'li-btn-blue-bg',
            ];
        }

        //生成表单
        return $this->layerEdit([
            "table" => [
                [
                    $this->tableShowButton($button),
                ],
                [
                    "<span class='small-title'>基础业务</span>"
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('outsourceStrictPick', 1, '按委外加工单严格执行领料', $setting['outsourceStrictPick'])
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('outsourceStrictInStock', 1, '按委外加工单严格执行入库/质检', $setting['outsourceStrictInStock'])
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('outsourceProcessIn', 1, '按委外加工单领料控制入库/质检', $setting['outsourceProcessIn']['option'])
                ],
                [
                    "&emsp;控制方式&emsp;" . radio(array('name' => 'outsourceProcessInMethod', 'value' => ['pick' => '按照委外发料齐套数量严格入库/质检', 'afterPick' => '生产有领料后方可入库/质检'], 'checked' => $setting['outsourceProcessIn']['method']))
                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('reverseCheck', 1, '委外发料（退料）单新增/修改/删除时，反向检查是否满足领料入库/质检的控制要求', $setting['reverseCheck'])
//                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('allowNewMaterial', 1, '委外发料时允许新增材料', $setting['allowNewMaterial'])
//                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('bomShowMethod', 1, '委外加工单BOM展示方式', $setting['bomShowMethod'])
//                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('outsourceBaseWithTax', 1, '委外基准价含税', $setting['outsourceBaseWithTax'])
//                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('outsourceTaxPrice', 1, '工艺路线委外价含税', $setting['outsourceTaxPrice'])
//                ],
//                [
//                    "<span class='small-title'>最高委外价控制</span>"
//                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('outsourcePriceCtrl', 1, '最高委外价控制', $setting['outsourcePriceCtrl']['option'])
//                ],
//                [
//                    "&emsp;控制时机&emsp;" . radio(array('name' => 'outsourcePriceCtrlTime', 'value' => ['保存', '复核'], 'checked' => $setting['outsourcePriceCtrl']['way']))
//                ],
//                [
//                    "&emsp;控制方式&emsp;" . radio(array('name' => 'outsourcePriceCtrlMethod', 'value' => ['提交', '密码', '禁止'], 'checked' => $setting['outsourcePriceCtrl']['method']))
//                ],
            ],
            'hidden' => hidden(array('name' => 'type', 'value' => $type)) . hidden(array('name' => 'id', 'value' => $info['id'] ?: suiji())),
            'button' => ' ',
        ]);
    }

    /**
     * 委外
     * @return false|string
     */
    public function outsourceEdit()
    {
        $id = $this->post('id');
        $setting = [
            'outsourceStrictPick' => $this->post('outsourceStrictPick') ?: 0,
            'outsourceStrictInStock' => $this->post('outsourceStrictInStock') ?: 0,
            'outsourceProcessIn' => [
                'option' => $this->post('outsourceProcessIn') ?: 0,
                'method' => $this->post('outsourceProcessInMethod') ?: ''
            ],
            'reverseCheck' => $this->post('reverseCheck') ?: 0,
            'allowNewMaterial' => $this->post('allowNewMaterial') ?: 0,
            'bomShowMethod' => $this->post('bomShowMethod') ?: 0,
            'outsourceBaseWithTax' => $this->post('outsourceBaseWithTax') ?: 0,
            'outsourceTaxPrice' => $this->post('outsourceTaxPrice') ?: 0,
            'outsourcePriceCtrl' => [
                'option' => $this->post('outsourcePriceCtrl') ?: 0,
                'way' => $this->post('outsourcePriceCtrlTime') ?: '',
                'method' => $this->post('outsourcePriceCtrlMethod') ?: ''
            ],
        ];
        //赋值
        $field = [
            "type" => $this->post('type'),
            'setting' => json_encode($setting, 320)
        ];
        $annotation = [
            'type' => '类型',
        ];
        $rules = [
            'type' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }

        $info = query(self::table, " id = '" . $id . "' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑的权限";
        } elseif (empty($id)) {
            $json['warn'] = "ID号为空";
        } elseif (empty($info['id'])) {
            $field = array_merge($field, ["id" => $id, 'coid' => self::$coid]);
            $json['warn'] = insert(["table" => self::table, "field" => $field]);
        } else {
            $json['warn'] = update(["table" => self::table, "field" => $field, "where" => "id = '" . $id . "'"]);
        }
        if (in_array($json['warn'], array("新增成功", "更新成功"))) {
            //添加日志
            $type = mb_substr($json['warn'], 0, 2, 'utf-8');
            $text = $this->control['name'] . $type . "了一个选项设置：" . $id;
            $this->logText(array("type" => self::page, "text" => $text));
            //提示
            $_SESSION['warn'] = $json['warn'];
            $json['warn'] = 2;
            $json['href'] = root . 'control/adIndex.html?cla=' . self::page . '&fun=home&type=' . $field['type'];
        }
        //返回
        resp:
        return json_encode($json, 320);
    }

    /**
     * 物流
     * @param $type
     * @return string
     */
    private function logistics($type): string
    {
        //数据查询
        $info = query(self::table, " coid = '".self::$coid."' and type = '" . $type . "' ");
        $setting = [
            'autoOutStock' => 0,
            'sourceOrder' => [],
        ];
        $setting = $info['setting'] ? json_decode($info['setting'], true) : $setting;
        //按钮
        $button = [];
        if ($this->power(self::page, "edit")) {
            $button[] = [
                "name" => "保存",
                "type" => "点击事件",
                "fun" => "subForm('" . self::page . "HomeRightJsonSearchForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=logisticsEdit')",
                'style' => 'li-btn-blue-bg',
            ];
        }

        //生成表单
        return $this->layerEdit([
            "table" => [
                [
                    $this->tableShowButton($button),
                ],
                [
                    "<span class='small-title'>基础业务</span>"
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('autoOutStock', 1, '确认发货时自动销售出库', $setting['autoOutStock'])
                ],
                [
                    "选择作为物流发货依据的源单&emsp;" . checkbox(array('name' => 'sourceOrder', 'value' => ['saleOrder' => '销售订单', 'saleSendOrder' => '销售发货单', 'saleOutOrder' => '销售出库单'], 'checked' => $setting['sourceOrder']))
                ],
            ],
            'hidden' => hidden(array('name' => 'type', 'value' => $type)) . hidden(array('name' => 'id', 'value' => $info['id'] ?: suiji())),
            'button' => ' ',
        ]);
    }

    public function logisticsEdit()
    {
        $id = $this->post('id');
        $setting = [
            'autoOutStock' => $this->post('autoOutStock') ?: 0,
            'sourceOrder' => $this->post('sourceOrder') ?: [],
        ];
        //赋值
        $field = [
            "type" => $this->post('type'),
            'setting' => json_encode($setting, 320)
        ];
        $annotation = [
            'type' => '类型',
        ];
        $rules = [
            'type' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }

        $info = query(self::table, " id = '" . $id . "' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑的权限";
        } elseif (empty($id)) {
            $json['warn'] = "ID号为空";
        } elseif (empty($info['id'])) {
            $field = array_merge($field, ["id" => $id, 'coid' => self::$coid]);
            $json['warn'] = insert(["table" => self::table, "field" => $field]);
        } else {
            $json['warn'] = update(["table" => self::table, "field" => $field, "where" => "id = '" . $id . "'"]);
        }
        if (in_array($json['warn'], array("新增成功", "更新成功"))) {
            //添加日志
            $type = mb_substr($json['warn'], 0, 2, 'utf-8');
            $text = $this->control['name'] . $type . "了一个选项设置：" . $id;
            $this->logText(array("type" => self::page, "text" => $text));
            //提示
            $_SESSION['warn'] = $json['warn'];
            $json['warn'] = 2;
            $json['href'] = root . 'control/adIndex.html?cla=' . self::page . '&fun=home&type=' . $field['type'];
        }
        //返回
        resp:
        return json_encode($json, 320);
    }

    /**
     * 库存
     * @param $type
     * @return string
     */
    private function inventoryOrder($type): string
    {
        //数据查询
        $info = query(self::table, " coid = '".self::$coid."' and type = '" . $type . "' ");
        $setting = [
            'outAllowZero' => 0,
            'autoBatch' => [
                'option' => 0,
                'method' => ''
            ],
            'inventoryStockWarn' => 0,
            'inventoryStockCtrl' => 0,
            'zeroOutCtrl' => 0,
            'checkCtrl' => 0,
            'inStockLimit' => 0,
            'outStockLimit' => 0,
            'noCheckManage' => 0,
            'warehousePosition' => [
                'option' => 0,
                'auto' => 0,
                'method' => ''
            ],
            'inventoryCtrl' => [
                'option' => 0,
                'val' => []
            ],
            'mrpWarehouse' => [],
            'estimateIn' => [],
            'estimateOut' => []
        ];
        $setting = $info['setting'] ? json_decode($info['setting'], true) : $setting;
        //按钮
        $button = [];
        if ($this->power(self::page, "edit")) {
            $button[] = [
                "name" => "保存",
                "type" => "点击事件",
                "fun" => "subForm('" . self::page . "HomeRightJsonSearchForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=inventoryOrderEdit')",
                'style' => 'li-btn-blue-bg',
            ];
        }
        $warehouseOption = [];
        $all = find(array('table' => 'warehouse', "where" => "coid = '" . self::$coid . "' and state = '启用' order by time asc"));
        foreach ($all['array'] as $array) {
            $warehouseOption[$array['id']] = $array['name'];
        }
        $orderGroup = [
            'purchaseWaitIn' => "采购待入库",
            'allocationWaitIn' => "调拨待入库",
            'machiningWaitIn' => "生产待入库",
            'outsourceWaitIn' => "委外待入库",
            'otherWaitIn' => "其他待入库",
        ];
        $li = '';
        $index = 0;
        foreach ($orderGroup as $key => $val) {
            $li .= "<li>" . businessVoucherSettingClass::singleCheckBox('estimateIn[]', $key, "$val", $setting['estimateIn'][$index] ?? '') . "</li>";
            $index++;
        }
        $outOrderGroup = [
            'sendWaitIn' => "发货待出库",
            'pickWaitOut' => "领料待出库",
            'ingOrderWaitOut' => "配料待出库",
            'outsourceWaitOut' => "委外发料待出库",
            'allocationWaitOut' => "调拨待出库",
            'otherWaitOut' => "其他待出库",
        ];
        $outLi = '';
        $index = 0;
        foreach ($outOrderGroup as $key => $val) {
            $outLi .= "<li>" . businessVoucherSettingClass::singleCheckBox('estimateOut[]', $key, "$val", $setting['estimateOut'][$index] ?? '') . "</li>";
            $index++;
        }
        $inventoryHtml = <<<eof
<div style="display: flex;flex-direction: row">
    <div class="ul-div">可用库存</div>
    <div class="char-div">=</div>
    <div class="ul-div">现存量</div>
    <div class="char-div">+</div>
    <div>
        <div class="ul-div">预计入库量</div>
        <div class="select-ul"><ul>$li</ul></div>
    </div>
    <div class="char-div">-</div>
    <div>
        <div class="ul-div">预计出库量</div>
        <div class="select-ul estimateOut" style="text-align: left"><ul>$outLi</ul></div>
    </div>
    <!--<div class="char-div">-</div>
    <div class="ul-div">锁定量</div>-->
</div>
<style>
.ul-div{width:196px;height: 36px;text-align: center;line-height: 36px;border: 1px solid rgba(215, 215, 215, 1)}
.char-div{height: 36px;line-height: 36px;text-align: center;width: 20px}
.select-ul{text-align: center;border: 1px solid rgba(215, 215, 215, 1);border-top: none}
.estimateOut ul li{padding-left: 50px}
</style>
eof;

        //生成表单
        return $this->layerEdit([
            "table" => [
                [
                    $this->tableShowButton($button),
                ],
                [
                    "<span class='small-title'>基础设置</span>"
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('outAllowZero', 1, "仓库允许零库存出库", $setting['outAllowZero'])
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('autoBatch', 1, "自动带出批号", $setting['autoBatch']['option']) . "&emsp;" .hidden(['name' => 'autobatchMethod','value'=>'现存量']) /*radio(array('name' => 'autobatchMethod', 'value' => ['可用量', '现存量'], 'checked' => $setting['autoBatch']['method']))*/
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('inventoryStockWarn', 1, "最高最低库存预警包含不参与可用量仓库", $setting['inventoryStockWarn'])
                ],
                [
                    "最低最高库存控制&emsp;" . radio(array('name' => 'inventoryStockCtrl', 'value' => ['1'=>'禁止', '0'=>'提示'], 'checked' => $setting['inventoryStockCtrl']))
                ],
                /*[
                    businessVoucherSettingClass::singleCheckBox('noCheckManage', 1, "不核算仓管理", $setting['noCheckManage'])
                ],*/
                [
                    businessVoucherSettingClass::singleCheckBox('zeroOutCtrl', 1, "倒冲时进行零出库控制", $setting['zeroOutCtrl'])
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('checkCtrl', 1, "库存需要复核", $setting['checkCtrl'])
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('inStockLimit', 1, "入库数量允许超过源单数量", isset($setting['inStockLimit'])?$setting['inStockLimit']:0)
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('outStockLimit', 1, "出库数量允许超过源单数量", isset($setting['outStockLimit'])?$setting['outStockLimit']:0)
                ],
                [
                    "<span class='small-title'>货位管理</span>"
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('warehousePosition', 1, "货位管理", $setting['warehousePosition']['option'])
                ],
                [
                    "&emsp;" . businessVoucherSettingClass::singleCheckBox('autoPosition', 1, "自动匹配货位", $setting['warehousePosition']['auto']) . "&emsp;" . radio(array('name' => 'warehousePositionMethod', 'value' => ['auto' => '自动带出默认货位', 'material' => '按货物现存量带出货位'], 'checked' => $setting['warehousePosition']['method']))
                ],
                [
                    "<span class='small-title'>可用量控制</span>"
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('inventoryCtrl', 1, '可用量控制', $setting['inventoryCtrl']['option']) . "&emsp;" . checkbox(array('name' => 'inventoryCtrlVal', 'value' => ['saleSendOrder' => "销售发货单", 'inventoryOrder' => "库存单据"], 'checked' => $setting['inventoryCtrl']['val'])) /*'saleOrder' => "销售订单", */
                ],
                [
                    "参与MRP运算仓库：&emsp;" . checkbox(array('name' => 'mrpWarehouse', 'value' => $warehouseOption, 'checked' => $setting['mrpWarehouse']))
                ],
                [
                    "<span class='small-title'>可用库存参数</span>"
                ],
                [
                    $inventoryHtml
                ]
            ],
            'hidden' => hidden(array('name' => 'type', 'value' => $type)) . hidden(array('name' => 'id', 'value' => $info['id'] ?: suiji())),
            'button' => ' ',
        ]);
    }

    /**
     * 库存
     */
    public function inventoryOrderEdit()
    {
        $id = $this->post('id');
        $setting = [
            'outAllowZero' => $this->post('outAllowZero') ?: 0,
            'autoBatch' => [
                'option' => $this->post('autoBatch') ?: 0,
                'method' => $this->post('autobatchMethod') ?: ''
            ],
            'inventoryStockWarn' => $this->post('inventoryStockWarn') ?: 0,
            'inventoryStockCtrl' => $this->post('inventoryStockCtrl') ?: 0,
            'zeroOutCtrl' => $this->post('zeroOutCtrl') ?: 0,
            'checkCtrl' => $this->post('checkCtrl') ?: 0,
            'inStockLimit' => $this->post('inStockLimit') ?: 0,
            'outStockLimit' => $this->post('outStockLimit') ?: 0,
            'noCheckManage' => $this->post('noCheckManage') ?: 0,
            'warehousePosition' => [
                'option' => $this->post('warehousePosition') ?: 0,
                'auto' => $this->post('autoPosition') ?: 0,
                'method' => $this->post('warehousePositionMethod') ?: ''
            ],
            'inventoryCtrl' => [
                'option' => $this->post('inventoryCtrl') ?: 0,
                'val' => $this->post('inventoryCtrlVal') ?: []
            ],
            'mrpWarehouse' => $this->post('mrpWarehouse') ?: [],
            'estimateIn' => $this->post('estimateIn') ?: [],
            'estimateOut' => $this->post('estimateOut') ?: []
        ];
        //赋值
        $field = [
            "type" => $this->post('type'),
            'setting' => json_encode($setting, 320)
        ];
        $annotation = [
            'type' => '类型',
        ];
        $rules = [
            'type' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }

        $info = query(self::table, " id = '" . $id . "' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑的权限";
        } elseif (empty($id)) {
            $json['warn'] = "ID号为空";
        } elseif (empty($info['id'])) {
            $field = array_merge($field, ["id" => $id, 'coid' => self::$coid]);
            $json['warn'] = insert(["table" => self::table, "field" => $field]);
        } else {
            $json['warn'] = update(["table" => self::table, "field" => $field, "where" => "id = '" . $id . "'"]);
        }
        if (in_array($json['warn'], array("新增成功", "更新成功"))) {
            //添加日志
            $type = mb_substr($json['warn'], 0, 2, 'utf-8');
            $text = $this->control['name'] . $type . "了一个选项设置：" . $id;
            $this->logText(array("type" => self::page, "text" => $text));
            //提示
            $_SESSION['warn'] = $json['warn'];
            $json['warn'] = 2;
            $json['href'] = root . 'control/adIndex.html?cla=' . self::page . '&fun=home&type=' . $field['type'];
        }
        //返回
        resp:
        return json_encode($json, 320);
    }

    /**
     * 核算
     * @param $type
     * @return string
     */
    private function accounting($type): string
    {
        //数据查询
        $info = query(self::table, " coid = '".self::$coid."' and type = '" . $type . "' ");
        $setting = [
            'inStockPrice' => '',
            'outStockPrice' => '',
            'refundPrice' => '',
            'costRate' => [
                'option' => 0,
                'rate' => '',
            ],
            'costValueMethod' => '',
            'machiningInOrderShowDetail' => 0,
        ];
        $setting = $info['setting'] ? json_decode($info['setting'], true) : $setting;
        //按钮
        $button = [];
        if ($this->power(self::page, "edit")) {
            $button[] = [
                "name" => "保存",
                "type" => "点击事件",
                "fun" => "subForm('" . self::page . "HomeRightJsonSearchForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=accountingEdit')",
                'style' => 'li-btn-blue-bg',
            ];
        }

        //生成表单
        return $this->layerEdit([
            "table" => [
                [
                    $this->tableShowButton($button),
                ],
                [
                    "<span class='small-title'>计价规则</span>"
                ],
                [
                    "&emsp;入库带出单价&emsp;" . radio(array('name' => 'inStockPrice', 'value' => ['上次出库成本', '参考成本', '结存成本', '上次入库成本'], 'checked' => $setting['inStockPrice']))
                ],
                [
                    "&emsp;出库带出单价&emsp;" . radio(array('name' => 'outStockPrice', 'value' => ['上次出库成本', '参考成本', '上次入库成本'], 'checked' => $setting['outStockPrice']))
                ],
                [
                    "&emsp;退货/退料出库带出单价&emsp;" . radio(array('name' => 'refundPrice', 'value' => ['上次出库成本', '参考成本', '结存成本', '上次入库成本'], 'checked' => $setting['refundPrice']))
                ],
                [
                    "<span class='small-title'>参考成本取价设置</span>"
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('costRate', 1, "当按计价规则取的成本与参考成本差异率超&nbsp;<input name='rate' type='number' style='width: 60px' value='{$setting['costRate']['rate']}'>%时，取参考成本", $setting['costRate']['option'])
                ],
                [
                    "<span class='small-title'>允许循环材料成本取值方式</span>"
                ],
                [
                    "&emsp;允许循环材料成本取值方式&emsp;" . radio(array('name' => 'costValueMethod', 'value' => ['参考成本', '结存成本', '记账成本', '手工录入'], 'checked' => $setting['costValueMethod']))
                ],
                [
                    "<span class='small-title'>产成品入库单显示成本明细</span>"
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('machiningInOrderShowDetail', 1, '产成品入库单显示成本明细', $setting['machiningInOrderShowDetail'])
                ],
            ],
            'hidden' => hidden(array('name' => 'type', 'value' => $type)) . hidden(array('name' => 'id', 'value' => $info['id'] ?: suiji())),
            'button' => ' ',
        ]);
    }

    /**
     * 核算
     * @return false|string
     */
    public function accountingEdit()
    {
        $id = $this->post('id');
        $setting = [
            'inStockPrice' => $this->post('inStockPrice') ?: '',
            'outStockPrice' => $this->post('outStockPrice') ?: '',
            'refundPrice' => $this->post('refundPrice') ?: '',
            'costRate' => [
                'option' => $this->post('costRate') ?: 0,
                'rate' => $this->post('rate') ?: 0,
            ],
            'costValueMethod' => $this->post('costValueMethod') ?: '',
            'machiningInOrderShowDetail' => $this->post('machiningInOrderShowDetail') ?: 0,
        ];
        //赋值
        $field = [
            "type" => $this->post('type'),
            'setting' => json_encode($setting, 320)
        ];
        $annotation = [
            'type' => '类型',
        ];
        $rules = [
            'type' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }

        $info = query(self::table, " id = '" . $id . "' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑的权限";
        } elseif (empty($id)) {
            $json['warn'] = "ID号为空";
        } elseif (empty($info['id'])) {
            $field = array_merge($field, ["id" => $id, 'coid' => self::$coid]);
            $json['warn'] = insert(["table" => self::table, "field" => $field]);
        } else {
            $json['warn'] = update(["table" => self::table, "field" => $field, "where" => "id = '" . $id . "'"]);
        }
        if (in_array($json['warn'], array("新增成功", "更新成功"))) {
            //添加日志
            $type = mb_substr($json['warn'], 0, 2, 'utf-8');
            $text = $this->control['name'] . $type . "了一个选项设置：" . $id;
            $this->logText(array("type" => self::page, "text" => $text));
            //提示
            $_SESSION['warn'] = $json['warn'];
            $json['warn'] = 2;
            $json['href'] = root . 'control/adIndex.html?cla=' . self::page . '&fun=home&type=' . $field['type'];
        }
        //返回
        resp:
        return json_encode($json, 320);
    }

    /**
     * 生产
     */
    private function machiningOrder($type)
    {
        //数据查询
        $info = query(self::table, " coid = '".self::$coid."' and type = '" . $type . "' ");
        $setting = [
            'beyondPurchasePlan' => 0,
            'beyondMachiningPlan' => 0,
            'beyondOutsourcePlan' => 0,
            'machiningOrderStrict' => 0,
            'machiningOrderProcessStrict' => [
                'option' => 0,
                'method' => '',
            ],
            'machiningOrderStrictIn' => 0,
            'machiningOrderPickStrict' => [
                'option' => 0,
                'method' => '',
            ],
            'reverseCheck' => 0,
            'machiningAllowAdd' => 0,
            'materialControlAfterSend' => [
                'option' => 0,
                'method' => '',
            ],
            'machiningOrderBom' => [
                'option' => 0,
                'method' => '',
            ],
            'autoNewSendOrder' => 0,
            'withOutMaterial' => 0,
            'withOutBom' => 0,
            'processReportByFlow' => [
                'option' => 0,
                'method' => '',
            ],
            'productWithOutCheck' => [
                'option' => 0,
                'method' => '',
                'way' => '',
            ],
            'mobileProcessChoose' => [
                'option' => 0,
                'method' => '',
            ],
            'mobileProcessDefaultNum' => [
                'option' => 0,
                'method' => '',
                'num' => '',
            ],
            'piecePrice' => [
                'option' => 0,
                'method' => '',
            ],
            'mobileProcessSplit' => 0,
            'processSecUnit' => [
                'option' => 0,
                'method' => '',
            ],
            'allowMoreProcessNum' => 0,
            'productCtrlMethod'=>'productCard'
        ];
        $setting = $info['setting'] ? json_decode($info['setting'], true) : $setting;
        //按钮
        $button = [];
        if ($this->power(self::page, "edit")) {
            $button[] = [
                "name" => "保存",
                "type" => "点击事件",
                "fun" => "subForm('" . self::page . "HomeRightJsonSearchForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=machiningOrderEdit')",
                'style' => 'li-btn-blue-bg',
            ];
        }

        //生成表单
        return $this->layerEdit([
            "table" => [
                [
                    $this->tableShowButton($button),
                ],
//                [
//                    "<span class='small-title'>物料需求计划</span>"
//                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('beyondPurchasePlan', 1, '允许超采购计划下单', $setting['beyondPurchasePlan'])
//                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('beyondMachiningPlan', 1, '允许超生产计划下单', $setting['beyondMachiningPlan'])
//                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('beyondOutsourcePlan', 1, '允许超委外计划下单', $setting['beyondOutsourcePlan'])
//                ],
                [
                    "<span class='small-title'>物料控制</span>"
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('machiningOrderStrict', 1, '按照生产加工单严格执行领料', $setting['machiningOrderStrict'])
                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('machiningOrderProcessStrict', 1, '按照生产加工单严格进行工序汇报', $setting['machiningOrderProcessStrict']['option'])
//                ],
//                [
//                    "&emsp;控制方式&emsp;" . radio(array('name' => 'machiningOrderProcessStrictMethod', 'value' => ['提交', '密码', '禁止'], 'checked' => $setting['machiningOrderProcessStrict']['method']))
//                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('machiningOrderStrictIn', 1, '按照生产加工单严格执行入库/质检', $setting['machiningOrderStrictIn'])
//                ],
                [
                    businessVoucherSettingClass::singleCheckBox('machiningOrderPickStrict', 1, '按照生产加工单领料控制入库/质检', $setting['machiningOrderPickStrict']['option'])
                ],
                [
                    "&emsp;控制方式&emsp;" . radio(array('name' => 'machiningOrderPickStrictMethod', 'value' => ['pick' => '按照生产领料齐套数量严格入库/质检', 'afterPick' => '生产有领料后方可入库/质检'], 'checked' => $setting['machiningOrderPickStrict']['method']))
                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('reverseCheck', 1, '材料出库单(含退料)新增/修改/删除时，反向检查是否满足领料入库/质检的控制要求', $setting['reverseCheck'])
//                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('machiningAllowAdd', 1, '生产补料时允许新增材料', $setting['machiningAllowAdd'])
//                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('materialControlAfterSend', 1, '启用派工后加工单材料录入控制', $setting['materialControlAfterSend']['option']) . "&emsp;" . radio(array('name' => 'materialControlAfterSendVal', 'value' => ['no' => '可不录入', 'all' => '所有产品必须录入', 'anyOne' => '任意产品录入即可'], 'checked' => $setting['materialControlAfterSend']['method']))
//                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('machiningOrderBom', 1, '生产加工单BOM展开方式默认值', $setting['machiningOrderBom']['option']) . "&emsp;" . radio(array('name' => 'machiningOrderBomVal', 'value' => ['单阶', '尾阶'], 'checked' => $setting['machiningOrderBom']['method']))
//                ],
                [
                    "<span class='small-title'>生产计划</span>"
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('autoNewSendOrder', 1, '生产计划生效自动生成派工单', $setting['autoNewSendOrder'])
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('withOutMaterial', 1, '生产计划无需所需物料', $setting['withOutMaterial'])
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('withOutBom', 1, '生产无需BOM表', $setting['withOutBom'])
                ],
                [
                    "<span class='small-title'>生产控制</span>"
                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('processReportByFlow', 1, '工序汇报严格按工序流程控制', $setting['processReportByFlow']['option'])
//                ],
//                [
//                    "&emsp;控制方式&emsp;" . radio(array('name' => 'processReportByFlowMethod', 'value' => ['提交', '密码', '禁止'], 'checked' => $setting['processReportByFlow']['method']))
//                ],
                [
                    businessVoucherSettingClass::singleCheckBox('productWithOutCheck', 1, '未启用产成品检验流程的产成品入库数量控制', $setting['productWithOutCheck']['option'])
                ],
                [
                    "&emsp;控制方式&emsp;" . radio(array('name' => 'productWithOutCheckMethod', 'value' => ['提交', '密码', '禁止'], 'checked' => $setting['productWithOutCheck']['method']))
                ],
                [
                    "&emsp;控制依据&emsp;" . radio(array('name' => 'productWithOutCheckWay', 'value' => ['endNum' => '末工序合格数量', 'endAndFailed' => '末工序合格+不合格数量', 'endAndAllFailed' => '末工序合格+全部工序不合格数量'], 'checked' => $setting['productWithOutCheck']['way']))
                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('mobileProcessChoose', 1, '移动端工序汇报单选单方式', $setting['mobileProcessChoose']['option']) . "&emsp;" . radio(array('name' => 'mobileProcessChooseMethod', 'value' => ['product' => '加工单+产品', 'process' => '加工单+产品+工序'], 'checked' => $setting['mobileProcessChoose']['method']))
//                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('mobileProcessDefaultNum', 1, '移动端工序汇报数量默认值', $setting['mobileProcessDefaultNum']['option']) . "&emsp;" . radio(array('name' => 'mobileProcessChooseMethod', 'value' => ['processNum' => '可报工数量', 'default' => "默认报工数量&nbsp;<input name='mobileProcessDefaultProcessNum' type='number' style='width: 60px' min='0' value='{$setting['mobileProcessDefaultNum']['num']}'>", 'zero' => '空'], 'checked' => $setting['mobileProcessDefaultNum']['method']))
//                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('piecePrice', 1, '取计件工价设置工价存在多条时', $setting['piecePrice']['option']) . "&emsp;" . radio(array('name' => 'piecePriceMethod', 'value' => ['min' => '取最小值', 'max' => '取最大值', 'warn' => '提醒且不保存'], 'checked' => $setting['piecePrice']['method']))
//                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('mobileProcessSplit', 1, '移动端多工人按数量汇报提交时拆分行', $setting['mobileProcessSplit'])
//                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('processSecUnit', 1, '启用工序计价辅单位', $setting['processSecUnit']['option'])
//                ],
//                [
//                    "&emsp;工序辅数量改变时，计算&emsp;" . radio(array('name' => 'processSecUnitMethod', 'value' => ['换算率', '数量'], 'checked' => $setting['processSecUnit']['method']))
//                ],
                [
                    businessVoucherSettingClass::singleCheckBox('allowMoreProcessNum', 1, '工序派工时允许超加工单工序数量', $setting['allowMoreProcessNum'])
                ],
                [
                    "生产控制使用&emsp;" . radio(array('name' => 'productCtrlMethod', 'value' => ['productCard' => '生产流转卡', 'machiningSendOrder' => '生产派工单'], 'checked' => $setting['productCtrlMethod']??'productCard'))
                ],
            ],
            'hidden' => hidden(array('name' => 'type', 'value' => $type)) . hidden(array('name' => 'id', 'value' => $info['id'] ?: suiji())),
            'button' => ' ',
        ]);
    }

    /**
     * 生产
     * @return bool|string
     */
    public function machiningOrderEdit(): bool|string
    {
        $id = $this->post('id');
        $setting = [
            'beyondPurchasePlan' => $this->post('beyondPurchasePlan') ?: 0,
            'beyondMachiningPlan' => $this->post('beyondMachiningPlan') ?: 0,
            'beyondOutsourcePlan' => $this->post('beyondOutsourcePlan') ?: 0,
            'machiningOrderStrict' => $this->post('machiningOrderStrict') ?: 0,
            'machiningOrderProcessStrict' => [
                'option' => $this->post('machiningOrderProcessStrict') ?: 0,
                'method' => $this->post('machiningOrderProcessStrictMethod') ?: '',
            ],
            'machiningOrderStrictIn' => $this->post('machiningOrderStrictIn') ?: 0,
            'machiningOrderPickStrict' => [
                'option' => $this->post('machiningOrderPickStrict') ?: 0,
                'method' => $this->post('machiningOrderPickStrictMethod') ?: '',
            ],
            'reverseCheck' => $this->post('reverseCheck') ?: 0,
            'machiningAllowAdd' => $this->post('machiningAllowAdd') ?: 0,
            'materialControlAfterSend' => [
                'option' => $this->post('materialControlAfterSend') ?: 0,
                'method' => $this->post('materialControlAfterSendVal') ?: '',
            ],
            'machiningOrderBom' => [
                'option' => $this->post('machiningOrderBom') ?: 0,
                'method' => $this->post('machiningOrderBomVal') ?: '',
            ],
            'autoNewSendOrder' => $this->post('autoNewSendOrder') ?: 0,
            'withOutMaterial' => $this->post('withOutMaterial') ?: 0,
            'withOutBom' => $this->post('withOutBom') ?: 0,
            'processReportByFlow' => [
                'option' => $this->post('processReportByFlow') ?: 0,
                'method' => $this->post('processReportByFlowMethod') ?: '',
            ],
            'productWithOutCheck' => [
                'option' => $this->post('productWithOutCheck') ?: 0,
                'method' => $this->post('productWithOutCheckMethod') ?: '',
                'way' => $this->post('productWithOutCheckWay') ?: '',
            ],
            'mobileProcessChoose' => [
                'option' => $this->post('mobileProcessChoose') ?: 0,
                'method' => $this->post('mobileProcessChooseMethod') ?: '',
            ],
            'mobileProcessDefaultNum' => [
                'option' => $this->post('mobileProcessDefaultNum') ?: 0,
                'method' => $this->post('mobileProcessChooseMethod') ?: '',
                'num' => $this->post('mobileProcessDefaultProcessNum') ?: 0,
            ],
            'piecePrice' => [
                'option' => $this->post('piecePrice') ?: 0,
                'method' => $this->post('piecePriceMethod') ?: '',
            ],
            'mobileProcessSplit' => $this->post('mobileProcessSplit') ?: 0,
            'processSecUnit' => [
                'option' => $this->post('processSecUnit') ?: 0,
                'method' => $this->post('processSecUnitMethod') ?: '',
            ],
            'allowMoreProcessNum' => $this->post('allowMoreProcessNum') ?: 0,
            'productCtrlMethod'=>$this->post('productCtrlMethod')?:'productCard'
        ];
        //赋值
        $field = [
            "type" => $this->post('type'),
            'setting' => json_encode($setting, 320)
        ];
        $annotation = [
            'type' => '类型',
        ];
        $rules = [
            'type' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }

        $info = query(self::table, " id = '" . $id . "' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑的权限";
        } elseif (empty($id)) {
            $json['warn'] = "ID号为空";
        } elseif (empty($info['id'])) {
            $field = array_merge($field, ["id" => $id, 'coid' => self::$coid]);
            $json['warn'] = insert(["table" => self::table, "field" => $field]);
        } else {
            $json['warn'] = update(["table" => self::table, "field" => $field, "where" => "id = '" . $id . "'"]);
        }
        if (in_array($json['warn'], array("新增成功", "更新成功"))) {
            //添加日志
            $type = mb_substr($json['warn'], 0, 2, 'utf-8');
            $text = $this->control['name'] . $type . "了一个选项设置：" . $id;
            $this->logText(array("type" => self::page, "text" => $text));
            //提示
            $_SESSION['warn'] = $json['warn'];
            $json['warn'] = 2;
            $json['href'] = root . 'control/adIndex.html?cla=' . self::page . '&fun=home&type=' . $field['type'];
        }
        //返回
        resp:
        return json_encode($json, 320);
    }

    /**
     * 质量
     */
    private function qualityOrder($type): string
    {
        //数据查询
        $info = query(self::table, " coid = '".self::$coid."' and type = '" . $type . "' ");
        $setting = [
            'purchaseAutoInStock' => 0,
            'checkOrderDefault' => [
                'option' => 0,
                'val' => '',
            ],
            'checkOrderBad' => [
                'option' => 0,
                'val' => '',
            ],
            'productNumControll' => [
                'option' => 0,
                'method' => '',
                'way' => ''
            ],
            'maintainQualityOrder' => [
                'option' => 0,
                'val' => [],
            ],
            'diffPassAndFailedBatch' => [
                'option' => 0,
                'val' => '',
            ],
            'selfMadeOrderCheck' => [
                'option' => 0,
                'val' => [],
            ],
        ];
        $setting = $info['setting'] ? json_decode($info['setting'], true) : $setting;
        //按钮
        $button = [];
        if ($this->power(self::page, "edit")) {
            $button[] = [
                "name" => "保存",
                "type" => "点击事件",
                "fun" => "subForm('" . self::page . "HomeRightJsonSearchForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=qualityOrderEdit')",
                'style' => 'li-btn-blue-bg',
            ];
        }

        //生成表单
        return $this->layerEdit([
            "table" => [
                [
                    $this->tableShowButton($button),
                ],
                [
                    "<span class='small-title'>基础设置</span>"
                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('purchaseAutoInStock', 1, '免检存货到货单生效后自动入库', $setting['purchaseAutoInStock'])
//                ],
                [
                    businessVoucherSettingClass::singleCheckBox('checkOrderDefaultNum', 1, '检验单检验数量默认值', $setting['checkOrderDefault']['option']) . "&emsp;" . radio(array('name' => 'checkOrderDefaultVal', 'value' => ['单据数量', '空'], 'checked' => $setting['checkOrderDefault']['val']))
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('checkOrderBadNum', 1, '检验单修改不合格数量时', $setting['checkOrderBad']['option']) . "&emsp;" . radio(array('name' => 'checkOrderBadVal', 'value' => ['passNum' => '检验数量不变，计算合格数量', 'checkNum' => '合格数量不变，计算检验数量'], 'checked' => $setting['checkOrderBad']['val']))
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('productNumControll', 1, '成品报检单报检数量控制', $setting['productNumControll']['option'])
                ],
                [
                    "&emsp;控制方式&emsp;" . radio(array('name' => 'productNumControllMethod', 'value' => ['提交', '密码', '禁止'], 'checked' => $setting['productNumControll']['method']))
                ],
                [
                    "&emsp;控制依据&emsp;" . radio(array('name' => 'productNumControllWay', 'value' => ['finalProcess' => '末工序合格数量', 'finalProcessWithNum' => '末工序合格+不合格数量', 'finalProcessWithAllNum' => '末工序合格+全部工序不合格数量'], 'checked' => $setting['productNumControll']['way']))
                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('maintainQualityOrder', 1, '可维护批号的质检单据', $setting['maintainQualityOrder']['option']) . "&emsp;" . checkbox(array('name' => 'maintainQualityOrderVal', 'value' => ['getOrder' => '到货单', 'inspectionOrder' => '成品报检单', 'checkOrder' => '检验单'], 'checked' => $setting['maintainQualityOrder']['val']))
//                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('diffPassAndFailedBatch', 1, '检验单严控合格品与不合格品批号必须不同', $setting['diffPassAndFailedBatch']['option']) . "&emsp;" . radio(array('name' => 'diffPassAndFailedBatchVal', 'value' => ['yes' => '控制', 'no' => '不控制', 'noAndSame' => '不控制且不合格品批号与合格品默认一致'], 'checked' => $setting['diffPassAndFailedBatch']['val']))
//                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('selfMadeOrderCheck', 1, '自制入库单时需要检验的存货控制为不可入库', $setting['selfMadeOrderCheck']['option']) . "&emsp;" . checkbox(array('name' => 'selfMadeOrderCheckOrder', 'value' => ['purchaseOrder' => '采购入库单', 'machiningInOrder' => '生产入库单'], 'checked' => $setting['selfMadeOrderCheck']['val']))
//                ],
            ],
            'hidden' => hidden(array('name' => 'type', 'value' => $type)) . hidden(array('name' => 'id', 'value' => $info['id'] ?: suiji())),
            'button' => ' ',
        ]);
    }

    public function qualityOrderEdit(): bool|string
    {
        $id = $this->post('id');
        $setting = [
            'purchaseAutoInStock' => $this->post('purchaseAutoInStock') ?: 0,
            'checkOrderDefault' => [
                'option' => $this->post('checkOrderDefaultNum') ?: 0,
                'val' => $this->post('checkOrderDefaultVal') ?: '',
            ],
            'checkOrderBad' => [
                'option' => $this->post('checkOrderBadNum') ?: 0,
                'val' => $this->post('checkOrderBadVal') ?: '',
            ],
            'productNumControll' => [
                'option' => $this->post('productNumControll') ?: 0,
                'method' => $this->post('productNumControllMethod') ?: '',
                'way' => $this->post('productNumControllWay') ?: ''
            ],
            'maintainQualityOrder' => [
                'option' => $this->post('maintainQualityOrder') ?: 0,
                'val' => $this->post('maintainQualityOrderVal') ?: [],
            ],
            'diffPassAndFailedBatch' => [
                'option' => $this->post('diffPassAndFailedBatch') ?: 0,
                'val' => $this->post('diffPassAndFailedBatchVal') ?: '',
            ],
            'selfMadeOrderCheck' => [
                'option' => $this->post('selfMadeOrderCheck') ?: 0,
                'val' => $this->post('selfMadeOrderCheckOrder') ?: [],
            ],
        ];
        //赋值
        $field = [
            "type" => $this->post('type'),
            'setting' => json_encode($setting, 320)
        ];
        $annotation = [
            'type' => '类型',
        ];
        $rules = [
            'type' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }

        $info = query(self::table, " id = '" . $id . "' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑的权限";
        } elseif (empty($id)) {
            $json['warn'] = "ID号为空";
        } elseif (empty($info['id'])) {
            $field = array_merge($field, ["id" => $id, 'coid' => self::$coid]);
            $json['warn'] = insert(["table" => self::table, "field" => $field]);
        } else {
            $json['warn'] = update(["table" => self::table, "field" => $field, "where" => "id = '" . $id . "'"]);
        }
        if (in_array($json['warn'], array("新增成功", "更新成功"))) {
            //添加日志
            $type = mb_substr($json['warn'], 0, 2, 'utf-8');
            $text = $this->control['name'] . $type . "了一个选项设置：" . $id;
            $this->logText(array("type" => self::page, "text" => $text));
            //提示
            $_SESSION['warn'] = $json['warn'];
            $json['warn'] = 2;
            $json['href'] = root . 'control/adIndex.html?cla=' . self::page . '&fun=home&type=' . $field['type'];
        }
        //返回
        resp:
        return json_encode($json, 320);
    }


    /**
     * 往来账/出纳
     */
    private function currentAccount($type): string
    {
        //数据查询
        $info = query(self::table, " coid = '".self::$coid."' and type = '" . $type . "' ");
        $setting = [
            'purchaseNeedPay' => 0,
            'purchaseOrderForPay' => 0,
            'feeNeedApply' => 0,
            'otherPayNeedApply' => 0,
            'outsourceForPay' => 0,
            'endToBook' => 0,
            'cashAndBankAudit' => 0,
        ];
        $setting = $info['setting'] ? json_decode($info['setting'], true) : $setting;
        //按钮
        $button = [];
        if ($this->power(self::page, "edit")) {
            $button[] = [
                "name" => "保存",
                "type" => "点击事件",
                "fun" => "subForm('" . self::page . "HomeRightJsonSearchForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=currentAccountEdit')",
                'style' => 'li-btn-blue-bg',
            ];
        }

        //生成表单
        return $this->layerEdit([
            "table" => [
                [
                    $this->tableShowButton($button),
                ],
//                [
//                    "<span class='small-title'>付款申请</span>"
//                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('purchaseNeedPay', 1, '采购业务必有付款申请', $setting['purchaseNeedPay'])
//                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('purchaseOrderForPay', 1, '采购付款申请参照采购订单执行', $setting['purchaseOrderForPay'])
//                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('feeNeedApply', 1, '费用必有付款申请', $setting['feeNeedApply'])
//                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('otherPayNeedApply', 1, '其他应付业务必有付款申请', $setting['otherPayNeedApply'])
//                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('outsourceForPay', 1, '委外费用必有付款申请', $setting['outsourceForPay'])
//                ],
                [
                    "<span class='small-title'>出纳</span>"
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('endToBook', 1, '现结类单据生效时自动登记现金银行日记账', $setting['endToBook'])
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('cashAndBankAudit', 1, '现金银行日记账需要审核', $setting['cashAndBankAudit'])
                ],
            ],
            'hidden' => hidden(array('name' => 'type', 'value' => $type)) . hidden(array('name' => 'id', 'value' => $info['id'] ?: suiji())),
            'button' => ' ',
        ]);
    }

    public function currentAccountEdit(): bool|string
    {
        $id = $this->post('id');
        $setting = [
            'purchaseNeedPay' => $this->post('purchaseNeedPay') ?: 0,
            'purchaseOrderForPay' => $this->post('purchaseOrderForPay') ?: 0,
            'feeNeedApply' => $this->post('feeNeedApply') ?: 0,
            'otherPayNeedApply' => $this->post('otherPayNeedApply') ?: 0,
            'outsourceForPay' => $this->post('outsourceForPay') ?: 0,
            'endToBook' => $this->post('endToBook') ?: 0,
            'cashAndBankAudit' => $this->post('cashAndBankAudit') ?: 0,
        ];
        //赋值
        $field = [
            "type" => $this->post('type'),
            'setting' => json_encode($setting, 320)
        ];
        $annotation = [
            'type' => '类型',
        ];
        $rules = [
            'type' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }

        $info = query(self::table, " id = '" . $id . "' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑的权限";
        } elseif (empty($id)) {
            $json['warn'] = "ID号为空";
        } elseif (empty($info['id'])) {
            $field = array_merge($field, ["id" => $id, 'coid' => self::$coid]);
            $json['warn'] = insert(["table" => self::table, "field" => $field]);
        } else {
            $json['warn'] = update(["table" => self::table, "field" => $field, "where" => "id = '" . $id . "'"]);
        }
        if (in_array($json['warn'], array("新增成功", "更新成功"))) {
            //添加日志
            $type = mb_substr($json['warn'], 0, 2, 'utf-8');
            $text = $this->control['name'] . $type . "了一个选项设置：" . $id;
            $this->logText(array("type" => self::page, "text" => $text));
            //提示
            $_SESSION['warn'] = $json['warn'];
            $json['warn'] = 2;
            $json['href'] = root . 'control/adIndex.html?cla=' . self::page . '&fun=home&type=' . $field['type'];
        }
        //返回
        resp:
        return json_encode($json, 320);
    }


    /**
     * 总账
     */
    private function accountTotal($type): string
    {
        //数据查询
        $info = query(self::table, " coid = '".self::$coid."' and type = '" . $type . "' ");
        $setting = [
            'codeLength' => [2, 2, 2, 2],
            'sameAudit' => 0,
            'afterAuditMark' => 0,
            'cashierSign' => 0,
            'dayBook' => 0,
            'cashFlow' => 0,
            'deficit' => 0,
            'numPrecision' => [
                'num' => 2,
                'numLostZero' => 0
            ],
            'pricePrecision' => [
                'num' => 2,
                'priceLostZero' => 0
            ],
            'conversionRate' => 2,
            'invoicePrice' => 2,
            'lossRate' => 2,
            'depreciationrate' => 2,
            'assetCode' => 0,
            'depreciation' => 0
        ];
        $setting = $info['setting'] ? json_decode($info['setting'], true) : $setting;
        //按钮
        $button = [];
        if ($this->power(self::page, "edit")) {
            $button[] = [
                "name" => "保存",
                "type" => "点击事件",
                "fun" => "subForm('" . self::page . "HomeRightJsonSearchForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=accountTotalEdit')",
                'style' => 'li-btn-blue-bg',
            ];
        }
        $tr[] = ['级次', '级长'];
        $codeRule = [4, 3, 2];
        for ($i = 1; $i <= 6; $i++) {
            if ($i > 3) {
                $tr[] = [$i, text(array('name' => 'codeLength[]', 'class' => 'width100', 'type' => 'number', 'value' => $setting['codeLength'][$i - 4]))];
            } else {
                $tr[] = [$i, $codeRule[$i - 1]];
            }
        }

        //生成表单
        return $this->layerEdit([
            "table" => [
                [
                    $this->tableShowButton($button),
                ],
                [
                    "<span class='small-title'>科目设置</span>"
                ],
                [
                    "<div style='width: 400px'>" . $this->tableMany(array('tr' => $tr)) . "</div>"
                ],
                [
                    "<span class='small-title'>流程管控</span>"
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('sameAudit', 1, '制单人与审核人可为同一人', $setting['sameAudit'])
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('afterAuditMark', 1, '凭证需审核才可记账', $setting['afterAuditMark'])
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('cashierSign', 1, '出纳凭证必须经由出纳签字', $setting['cashierSign'])
                ],
                [
                    businessVoucherSettingClass::singleCheckBox('dayBook', 1, '出纳凭证生效后生成日记账', $setting['dayBook'])
                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('cashFlow', 1, '现金流量必录', $setting['cashFlow'])
//                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('deficit', 1, '资金及往来赤字控制', $setting['deficit'])
//                ],
                [
                    "<span class='small-title'>数据精度</span>"
                ],
                [
                    "数量小数位：" . select(array('name' => 'numPrecision', 'value' => $setting['numPrecision']['num'], 'option' => $this->numOption)) . "&emsp;" . businessVoucherSettingClass::singleCheckBox('numLostZero', 1, '舍零', $setting['numPrecision']['numLostZero'])
                ],
                [
                    "单价小数位：" . select(array('name' => 'pricePrecision', 'value' => $setting['pricePrecision']['num'], 'option' => $this->numOption)) . "&emsp;" . businessVoucherSettingClass::singleCheckBox('priceLostZero', 1, '舍零', $setting['pricePrecision']['priceLostZero'])
                ],
//                [
//                    "换算率小数位：" . select(array('name' => 'conversionRate', 'value' => $setting['conversionRate'], 'option' => $this->numOption))
//                ],
                [
                    "发票单价小数位：" . select(array('name' => 'invoicePrice', 'value' => $setting['invoicePrice'], 'option' => $this->numOption))
                ],
//                [
//                    "损耗率小数位：" . select(array('name' => 'lossRate', 'value' => $setting['lossRate'], 'option' => $this->numOption))
//                ],
                [
                    "折旧率小数位：" . select(array('name' => 'depreciationrate', 'value' => $setting['depreciationrate'], 'option' => $this->numOption))
                ],
                [
                    "<span class='small-title'>资产管理</span>"
                ],
//                [
//                    businessVoucherSettingClass::singleCheckBox('assetCode', 1, '移动端资产盘点，使用资产唯一码作为盘点依据', $setting['assetCode'])
//                ],
                [
                    businessVoucherSettingClass::singleCheckBox('depreciation', 1, '预计使用年限期满最后一个月提足折旧', $setting['depreciation'])
                ],
            ],
            'hidden' => hidden(array('name' => 'type', 'value' => $type)) . hidden(array('name' => 'id', 'value' => $info['id'] ?: suiji())),
            'button' => ' ',
        ]);
    }

    /*总账*/
    public function accountTotalEdit(): bool|string
    {
        $id = $this->post('id');
        $codeLenght = $this->post('codeLength') ?: [];
        $setting = [
            'codeLength' => $codeLenght,
            'sameAudit' => $this->post('sameAudit') ?: 0,
            'afterAuditMark' => $this->post('afterAuditMark') ?: 0,
            'cashierSign' => $this->post('cashierSign') ?: 0,
            'dayBook' => $this->post('dayBook') ?: 0,
            'cashFlow' => $this->post('cashFlow') ?: 0,
            'deficit' => $this->post('deficit') ?: 0,
            'numPrecision' => [
                'num' => $this->post('numPrecision') ?: 2,
                'numLostZero' => $this->post('numLostZero') ?: 0
            ],
            'pricePrecision' => [
                'num' => $this->post('pricePrecision') ?: 2,
                'priceLostZero' => $this->post('priceLostZero') ?: 0
            ],
            'conversionRate' => $this->post('conversionRate') ?: 2,
            'invoicePrice' => $this->post('invoicePrice') ?: 2,
            'lossRate' => $this->post('lossRate') ?: 2,
            'depreciationrate' => $this->post('depreciationrate') ?: 2,
            'assetCode' => $this->post('assetCode') ?: 0,
            'depreciation' => $this->post('depreciation') ?: 0,
        ];
        //赋值
        $field = [
            "type" => $this->post('type'),
            'setting' => json_encode($setting, 320)
        ];
        $annotation = [
            'type' => '类型',
        ];
        $rules = [
            'type' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $warn = '';
        foreach ($codeLenght as $val) {
            if ($val <= 0 || empty($val)) {
                $warn = '级长至少为1';
                break;
            }
        }

        $info = query(self::table, " id = '" . $id . "' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑的权限";
        } elseif (static::is_null_array($codeLenght)) {
            $json['warn'] = "请输入级长";
        } elseif (empty($id)) {
            $json['warn'] = "ID号为空";
        } elseif ($warn) {
            $json['warn'] = $warn;
        } elseif (empty($info['id'])) {
            $field = array_merge($field, ["id" => $id, 'coid' => self::$coid]);
            $json['warn'] = insert(["table" => self::table, "field" => $field]);
        } else {
            $json['warn'] = update(["table" => self::table, "field" => $field, "where" => "id = '" . $id . "'"]);
        }
        if (in_array($json['warn'], array("新增成功", "更新成功"))) {
            //添加日志
            $type = mb_substr($json['warn'], 0, 2, 'utf-8');
            $text = $this->control['name'] . $type . "了一个选项设置：" . $id;
            $this->logText(array("type" => self::page, "text" => $text));
            //提示
            $_SESSION['warn'] = $json['warn'];
            $json['warn'] = 2;
            $json['href'] = root . 'control/adIndex.html?cla=' . self::page . '&fun=home&type=' . $field['type'];
        }
        //返回
        resp:
        return json_encode($json, 320);
    }

}
